/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.farent.solutions.plugins.stripes.hyperstripes.core;

import com.farent.solutions.plugins.stripes.hyperstripes.spi.RenderKit;
import com.farent.solutions.plugins.stripes.hyperstripes.utils.Utils;
import java.util.EnumMap;
import java.util.Map;

/**
 * Creates a componentState for a component. This is statefull and comprise
 * the current state of the component in the view tree
 * @author user
 */
public class DefaultComponentTypeStateHelper implements ComponentTypeStateHelper
{
    private String name = Utils.EMPTY_STRING;
    
    private RenderKit renderKit = HyperStripesRenderKit.getInstance();
    
    private Map<PropertyKeys, Object> componentProperties =
            new EnumMap<PropertyKeys, Object>(PropertyKeys.class);

    private StripesApplicationContext hsContext ;

    @Override
    public String createUniqueId(String prefferedId) {
        if (prefferedId != null && !prefferedId.isEmpty() ) {
            return prefferedId;
        } else {
            Integer i = (Integer) componentProperties.get(PropertyKeys.lastId);
            int lastId = ((i != null) ? i : 0);
            componentProperties.put(PropertyKeys.lastId, ++lastId);
            return name + lastId;
        }
    }

    @Override
    public String createComponentId(ComponentModel model) {
        StringBuilder builder = new StringBuilder();
        if( model.getParent() != null )
        {
            builder.append(model.getParent().getId()).append(":");
        }
        if( model.getId() == null || model.getId().isEmpty() )
        {
            builder.append(createUniqueId(null));
        }
        else
        {
            builder.append(model.getId());
        }
        builder.trimToSize();
        model.setComponentId(builder.toString());
        return builder.toString();
    }

    @Override
    public void saveComponentKeyMap(String uniqueId, String componentId) {
        hsContext.getComponentKeyMap().put(uniqueId, componentId);
    }

    enum PropertyKeys {

        renderKitId, viewId, locale, lastId, beforePhase, afterPhase, phaseListeners, viewScope;

        private PropertyKeys() {
        }
    }

    @Override
    public RenderKit getRenderkit() {
       return renderKit;
    }
    @Override
    public void setHsContext(StripesApplicationContext ctx) {
        this.hsContext = ctx;
    }

    @Override
    public StripesApplicationContext getHsContext() {
        return hsContext;
    }
    
    @Override
    public String getName() {
        return name;
    }

    @Override
    public void setName(String name) {
        this.name = name;
    }
}
